<template>
	<div class="system-dicManager-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="920px">

			<el-card shadow="hover">
				<el-form ref="editDialogFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="80px">
					<el-row :gutter="35">


						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="所属分类" prop="parentId">
								<el-select clearable v-model="state.ruleForm.parentId">
									<el-option v-for="i in state.categoryList" :label="i.title" :value="i.id"
										:key="i.id"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="主标题" prop="title">
								<el-input v-model="state.ruleForm.title" placeholder="主标题" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="副标题" prop="subTitle">
								<el-input v-model="state.ruleForm.subTitle" placeholder="副标题" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="排序号" prop="articleSort">
								<el-input v-model="state.ruleForm.articleSort" placeholder="排序号" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="封面地址" prop="image">
								<uploadItem @changeImg="changeImgImage" :imgPath="state.ruleForm.image"></uploadItem>
							</el-form-item>
						</el-col>


						<!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="封面地址" prop="image">
								<el-input v-model="state.ruleForm.image" placeholder="封面地址" clearable></el-input>
							</el-form-item>
						</el-col> -->
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="文章内容" prop="articleContent">
								<Editor ref="mceEditorRef" :url="uploadActionUrl()"
									:value="state.ruleForm.articleContent" />
							</el-form-item>
						</el-col>









						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="是否启用">
								<el-switch v-model="state.ruleForm.status"></el-switch>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>


			</el-card>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>

<script setup lang="ts" name="systemDicDialog">
import { ElMessage } from 'element-plus';
import { reactive, ref, watch, defineAsyncComponent } from 'vue';



// 导入接口
import { useCommonApi } from '/@/api/common/index'



const uploadItem = defineAsyncComponent(() => import('./uploadItem.vue'));

// 引入组件
const Editor = defineAsyncComponent(() => import('/@/components/editor/index.vue'));
const mceEditorRef = ref();


const editDialogFormRef = ref();




// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);


const changeImgImage = (e) => {
	console.log(e)
	state.ruleForm.image = e.coverImage
}

const uploadActionUrl = () => {
	return (
		import.meta.env.VITE_PHOTO_API_URL + "/COMMON-SERVICE/personal/mongo/gridfs/upload"
	);
};




const validateArticleContent = (rule: any, value: any, callback: any) => {
	if (mceEditorRef.value.getContent() === '') {
		callback(new Error('请输入文章内容'))
	} else {
		callback()
	}
}


const rules = {
	parentId: [
		{ required: true, message: "请选择所属分类", trigger: "blur" }
	], title: [
		{ required: true, message: "请输入主标题", trigger: "blur" }
	], articleSort: [
		{ required: true, message: "请输入序号", trigger: "blur" }
	], subTitle: [
		{ required: true, message: "请输入副标题", trigger: "blur" }
	], articleContent: [
		{ validator: validateArticleContent, trigger: "blur" }]




}




const state = reactive({
	row: null as any,
	categoryList: [] as any,
	questionAnalysis: "",
	ruleForm: {
		parentId: "",
		title: "",
		subTitle: "",
		articleSort: "",
		image: "",
		status: false,
		articleContent: ""
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});



// 打开弹窗
const openDialog = async (type: string, row?: any) => {

	await articleCategory();

	if (type === 'edit') {
		state.row = row;
		state.ruleForm = {
			articleContent: row.articleContent,
			parentId: row.parentId,
			title: row.title,
			subTitle: row.subTitle,
			articleSort: row.articleSort,
			image: row.image,
			status: row.status == 1 ? true : false
		}
		state.dialog.title = '修改分类';
		state.dialog.submitTxt = '修 改';
	} else {
		state.ruleForm = {
			articleContent: "",
			parentId: "",
			title: "",
			subTitle: "",
			articleSort: "",
			image: "",
			status: false
		}
		state.dialog.title = '新增分类';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};



// 获取文章的分类
const articleCategory = async () => {
	let obj = {
		page: 1,
		limit: 100,
		nodeType: 1
	};
	try {
		let tempList = await useCommonApi().articleList(obj);
		state.categoryList = tempList.list;
	} catch (error: any) {
		ElMessage.warning(error.msg);
	}
}



// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};


// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async () => {

	editDialogFormRef.value.validate(async (valid: any) => {
		if (valid) {
			//检查参数列表

			try {
				if (state.dialog.type == 'edit') {
					let obj = Object.assign({}, {}, state.ruleForm) as any;
					obj.status = obj.status ? 1 : 0;
					obj = Object.assign({}, state.row, obj);
					obj.articleContent = mceEditorRef.value.getContent();
					await useCommonApi().updateArticle(obj);
				} else {
					let obj = Object.assign({}, {}, state.ruleForm) as any;
					obj.status = obj.status ? 1 : 0;
					obj.nodeType = 2;
					obj.articleContent = mceEditorRef.value.getContent();
					await useCommonApi().addArticle(obj);
				}
				ElMessage.success("操作成功");
				closeDialog(); // 关闭弹窗
				emit('refresh');
			} catch (error: any) {
				ElMessage.error("操作失败请稍后再试");
			}


		} else {
			ElMessage.warning("请检查数据的正确性！");
		}
	})



};




watch(
	() => state.dialog.isShowDialog,
	(newValue) => {
		if (newValue == true) {
		}
	}, { immediate: true }
);




// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss">
.el-select {
	width: 100% !important;
}



.system-dicManager-dialog-container {
	.bar_tools {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.el-table__expanded-cell {
		padding: 20px;
	}
}
</style>